# coding=utf-8
import sys
import re


def addMatch(matches, match, line):
    stat = matches.get(match, {"lineCount":0, "charCount":0, "charMin":99999999999, "charMax":0})
    stat["lineCount"] += 1
    lineCount = len(line)
    stat["charCount"] += lineCount
    if stat["charMin"] > lineCount:
        stat["charMin"] = lineCount
    if stat["charMax"] < lineCount:
        stat["charMax"] = lineCount
    matches[match] = stat

def handleLog(logFile, regexStr, matches):
    r = re.compile(regexStr)
    with open(logFile, "r") as log:
        for line in log:
            obj = r.search(line)
            if obj is None:
                continue
            match = obj.group(0)
            addMatch(matches, match, line)

def printMatch(matches):
    maxMatchLen = 0
    for match in matches:
        matchLen = len(match)
        if matchLen > maxMatchLen:
            maxMatchLen = matchLen
    logFormat = "{:<%d}\t{:<10}{:<15}{:<10}{:<8}{:<10}" %(maxMatchLen)

    print(logFormat.format('Match', 'Line', 'Total(KB)', 'Max', 'Min', 'Avg'))
    print(logFormat.format('-----', '----', '---------', '---', '---', '---'))
    for match, stat in matches.items():
        charCountWithKB = stat["charCount"] / 1000.0
        average = 1.0 * stat["charCount"] / stat["lineCount"]
        print(logFormat.format(match, stat["lineCount"], "%.1f" %(charCountWithKB),
              stat["charMax"], stat["charMin"], "%.1f" %(average)))

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print('usage: regex_str.sh {file} "{regex}"')
        exit(1)
    matches = {}
    handleLog(sys.argv[1], sys.argv[2], matches)
    printMatch(matches)